#include "domainmodel.h"

namespace IAlib
{

DomainModel::DomainModel() : m_actor_id("")
{
}

DomainModel::DomainModel(const DomainModel &model)
{
    m_actor_id = model.m_actor_id;
    for (int i = 0; i < model.m_missions.size(); i++)
    {
        addMission(*model.m_missions[i]);
    }
}

DomainModel::~DomainModel()
{
    for (int i = 0; i < m_missions.size(); i++)
    {
        delete(m_missions[i]);
    }
}

void DomainModel::addMission(const Mission &mission)
{
    Mission * newMission = new Mission(mission);
    m_missions.append(newMission);
}

void DomainModel::removeMission(const QString &mission_name)
{
    for ( int i = 0; i < m_missions.size(); i++ )
    {
        if (m_missions[i]->getName() == mission_name)
        {
            delete(m_missions[i]);
            m_missions.removeAt(i);
        }
    }
}

Mission * DomainModel::getMission(const QString &mission_name)
{
    bool exist = false;
    int i = 0;
    for ( i = 0; i < m_missions.size(); i++ )
    {
        if (m_missions[i]->getName() == mission_name)
        {
            exist = true;
            break;
        }
    }
    if (exist)
    {
        return m_missions[i];
    }
    else
    {
        return NULL;
    }
}

QDomElement DomainModel::toXML(QDomDocument &doc)
{
    QDomElement ele = doc.createElement("domainModel");
    ele.setAttribute("actor_id", m_actor_id);
    QDomElement missions = doc.createElement("missions");
    for (int i = 0; i < m_missions.size(); i++)
    {
        missions.appendChild(m_missions[i]->toXML(doc));
    }
    ele.appendChild(missions);
    return ele;
}

void DomainModel::fromXML(QDomElement ele)
{
    m_actor_id = ele.attribute("actor_id", "");
    QDomNode n = ele.firstChild();
    while (!n.isNull())
    {
        QDomElement e = n.toElement();
        if (e.tagName() == "missions")
        {
            QDomNode missionNode = e.firstChild();
            while (!missionNode.isNull())
            {
                Mission mission;
                mission.fromXML(missionNode.toElement());
                addMission(mission);
                missionNode = missionNode.nextSibling();
            }
        }
        n = n.nextSibling();
    }
}

DomainModel& DomainModel::operator=(const DomainModel& model)
{
    m_actor_id = model.m_actor_id;
    for (int i = 0; i < m_missions.size(); i++)
    {
        delete(m_missions[i]);
    }
    m_missions.clear();
    for (int i = 0; i < model.m_missions.size(); i++)
    {
        addMission(*model.m_missions[i]);
    }
    return *this;
}


}
